import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-11-16 14:38
 */
public class Demo4 {

    public static int count = 0;  //静态变量，可以被所有线程访问
    public static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public static void main(String[] args) throws InterruptedException {
        String name = Thread.currentThread().getName();
        System.out.println(name);
        int i = 1; //线程私有变量
        int totalCount = 100000;


        Thread thread1 = new Thread(() -> {

            Lock lock = readWriteLock.writeLock();
            for (int j = 0; j < totalCount; j++) {
                //可重入
                lock.lock();
                try{
                    count++;
                }finally {
                    lock.unlock();
                }
            }

        });
        Thread thread2 = new Thread(() -> {

            Lock lock = readWriteLock.readLock();
            for (int j = 0; j < totalCount; j++) {
                lock.lock();
                try{
                    int k = count;
                }finally {
                    lock.unlock();
                }
            }
        });
        Thread thread3 = new Thread(() -> {

            Lock lock = readWriteLock.readLock();
            for (int j = 0; j < totalCount; j++) {
                lock.lock();
                try{
                    int k = count;
                }finally {
                    lock.unlock();
                }
            }
        });
        thread1.start();
        thread2.start();
        thread3.start();

        thread1.join();
        thread2.join();

        System.out.println(count);
    }
}
